#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTRootView.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTLinkingManager.h>

#import "RNSAlipayManager.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "SCOutsideWebJumpToAppManager.h"
#import "AppDelegate+Setup.h"
#import "AppDelegate+SCPush.h"
#import "SCRNEventManager.h"
#import "SCOneLoginTool.h"
#import "SCLoginVC.h"
#import "Config.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//  self.moduleName = @"Shuaicheyeguan";
//  // You can add your custom initial props in the dictionary below.
//  // They will be passed down to the ViewController used by React Native.
//  self.initialProps = @{};
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginCtr) name:SCNOTIFICATION_LOGIN object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginInOrOut) name:SCNOTIFICATION_LOGIN_IN_OUT object:nil];
  
  [self setup];
  
  [self registerJPushWithOptions:launchOptions];
  
  launchOptions_ = launchOptions;
  [self RCTRootViewController];
  
  hasLoadedRnApp = NO;
  
  //取消暗黑适配
  if(@available(iOS 13.0,*)){
    self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
  }

  return YES;
}

- (void)RCTRootViewController {
  
  if ([Config sharedConfig].user.imToken) {
    [self registWechatEnt];
  }
  
  NSMutableDictionary *properties = [NSMutableDictionary dictionaryWithCapacity:0];
  
  properties[@"apiDomain"] = kSC_API_DOMAIN;
  properties[@"webDomain"] = kSC_WEB_DOMAIN;
  properties[@"imApiAddr"] = kSC_IM_API_ADDR;
  properties[@"imWsAddr"] = kSC_IM_WS_ADDR;
  
#ifdef APP_STORE
  properties[@"release"] = @(YES);
#else
  properties[@"release"] = @(NO);
  NSString *env = [[SCAppConfig sharedInstance] currentEnv];
  NSInteger apiType = 0;
  if ([env isEqualToString:@"dev"]) {
    apiType = 1;
  } else if ([env isEqualToString:@"test"]) {
    apiType = 2;
  } else if ([env isEqualToString:@"pro"]) {
   apiType = 3;
 }
  properties[@"apiType"] = @(apiType);
#endif
  
  properties[@"statusBarHeight"] = @([[UIApplication sharedApplication] statusBarFrame].size.height);
  
  NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:kSessionId];
  if (sessionId) {
    properties[@"sessionId"] = sessionId;
  }
    
  properties[@"userInfo"] = [self formatUser];
  
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions_];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                     moduleName:@"Shuaicheyeguan"
                                              initialProperties:properties];
  [SCRNEventManager shareInstance].bridge = rootView.bridge;
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  
  self.nav = [[SCNavigationController alloc]initWithRootViewController:rootViewController];
  [self.nav setNavigationBarHidden:YES animated:NO];
    
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  self.window.rootViewController = self.nav;
  [self.window makeKeyAndVisible];
}

- (NSString *)formatUser {
  User *user = [Config sharedConfig].user;
  if (!user) {
    return nil;
  }
  
  NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:0];
  if (user.phone) {
    userInfo[@"phone"] = user.phone;
  }
  if (user.face) {
    userInfo[@"face"] = user.face;
  }
  if (user.roleName) {
    userInfo[@"roleName"] = user.roleName;
  }
  if (user.merchantId) {
      NSString *merchantId = [NSString stringWithFormat:@"%d",user.merchantId];
    userInfo[@"merchantId"] = merchantId;
  }
  if (user.perms) {
    NSString *perms = [NSString stringWithFormat:@"%lld",user.perms];
    userInfo[@"perms"] = perms;
  }
  if (user.userId) {
      NSString *userId = [NSString stringWithFormat:@"%d",user.userId];
    userInfo[@"userId"] = userId;
  }
  if (user.username) {
    userInfo[@"username"] = user.username;
  }
  if (user.fullname) {
    userInfo[@"fullname"] = user.fullname;
  }
  if (user.merchantName) {
    userInfo[@"merchantName"] = user.merchantName;
  }
  if (user.merchantAbbreviation) {
    userInfo[@"merchantAbbreviation"] = user.merchantAbbreviation;
  }
  if (user.merchantLogoPic) {
    userInfo[@"merchantLogoPic"] = user.merchantLogoPic;
  }
  if (user.imToken) {
    userInfo[@"imToken"] = user.imToken;
  }
  if (user.imTokenExpireTimeSeconds) {
    userInfo[@"imTokenExpireTimeSeconds"] = @(user.imTokenExpireTimeSeconds);
  }
  if (user.imUserId) {
    userInfo[@"imUserId"] = user.imUserId;
  }
  userInfo[@"isFranchisee"] = @(user.isFranchisee);
  //caiyc 添加买手标识
  userInfo[@"buyerId"] = @(user.buyerId);
  userInfo[@"isExternalCarEntryUser"] = @(user.isExternalCarEntryUser);
  
  NSLog(@"[userInfo yy_modelToJSONString] = %@",[userInfo yy_modelToJSONString]);
  return [userInfo yy_modelToJSONString];
}

//登录
- (void)showLoginCtr
{
  UIViewController *rootViewController = [[UIViewController alloc] init];
  rootViewController.view.backgroundColor = [UIColor whiteColor];
  self.window.rootViewController = rootViewController;
  
  SCOneLoginTool *loginTool = [[SCOneLoginTool alloc] init];
  [loginTool requestIsOneLogin:YES viewController:rootViewController otherLogin:^() {
    
    SCLoginVC *loginVC = [[SCLoginVC alloc] init];
    loginVC.loginSuccess = ^{
      [self RCTRootViewController];
    };
    loginVC.isPresented = YES;
    loginVC.modalPresentationStyle = UIModalPresentationFullScreen;
    SCNavigationController *nc = [[SCNavigationController alloc] initWithRootViewController:loginVC];
    loginVC.hideNavigationBar = YES;
    nc.modalPresentationStyle = UIModalPresentationFullScreen;
    [rootViewController presentViewController:nc animated:YES completion:nil];
      
  }];
  loginTool.loginSuccess = ^{
    [self RCTRootViewController];
  };
  
}

- (void)loginInOrOut {
  if (![[NSUserDefaults standardUserDefaults] boolForKey:kIsLogin]) {
    [self showLoginCtr];
  }
}

// ios 8.x or older
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{
  if ([url.host isEqualToString:@"safepay"]) {
    //跳转支付宝钱包进行支付，处理支付结果
    [RNSAlipayManager handleCallback:url];
    return YES;
  } else {
    return [RCTLinkingManager application:application openURL:url
                        sourceApplication:sourceApplication annotation:annotation];
  }
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
  return [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
}

// ios 9.0+
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
  if ([url.host isEqualToString:@"shuaiche.com"]) {
    NSString *urlString = [url absoluteString];
    LogInfo(@"urlString = %@",urlString);
    if (hasLoadedRnApp) {
      [SCOutsideWebJumpToAppManager handleUrlString:urlString];
    } else {
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SCOutsideWebJumpToAppManager handleUrlString:urlString];
      });
    }
    
    return YES;
  }
  
  if ([url.host isEqualToString:@"safepay"]) {
    //跳转支付宝钱包进行支付，处理支付结果
    [RNSAlipayManager handleCallback:url];
  } else {
    return [RCTLinkingManager application:app openURL:url options:options];
  }
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end
